package com.dabai.sas.utils;

import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.webkit.ValueCallback;
import android.webkit.WebView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class AssetsUtils {

    private static final String TAG = "DABAI";



    /**
     * 加载assets内的文本文件
     * @param context
     * @param path
     * @return
     */
    public static String loadAssetsText(Context context, String path) {

        String jsStr = "";
        try {
            InputStream in = context.getAssets().open(path);
            byte[] buff = new byte[1024];
            ByteArrayOutputStream fromFile = new ByteArrayOutputStream();
            do {
                int numRead = in.read(buff);
                if (numRead <= 0) {
                    break;
                }
                fromFile.write(buff, 0, numRead);
            } while (true);
            jsStr = fromFile.toString();
            in.close();
            fromFile.close();
            return jsStr;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "null";
    }

    /**
     * webView 加载Assets内的js 注入
     * 要写在onPageStarted内
     * @param webView
     * @param path
     */
    public static void loadJS(WebView webView, String path) {

        String jsStr = "";
        try {
            InputStream in = webView.getContext().getAssets().open(path);
            byte[] buff = new byte[1024];
            ByteArrayOutputStream fromFile = new ByteArrayOutputStream();
            do {
                int numRead = in.read(buff);
                if (numRead <= 0) {
                    break;
                }
                fromFile.write(buff, 0, numRead);
            } while (true);
            jsStr = fromFile.toString();
            in.close();
            fromFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(jsStr, value -> {
                //Log.d(TAG, "loadJS: "+value);
            });
        }

    }


}
